<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use QCloud\COSSTS\Sts;

class UploadController extends Controller
{
    public function getToken(Request $Request){
        $id = env('UPLOAD_APP_ID');
        $key = env('UPLOAD_APP_KEY');
        
        $sts = new Sts();
        $config = array(
            'url' => 'https://sts.tencentcloudapi.com/', // url和domain保持一致
            'domain' => 'sts.tencentcloudapi.com', // 域名，非必须，默认为 sts.tencentcloudapi.com
            'proxy' => '',
            'secretId' => $id, // 固定密钥,若为明文密钥，请直接以'xxx'形式填入，不要填写到getenv()函数中
            'secretKey' => $key, // 固定密钥,若为明文密钥，请直接以'xxx'形式填入，不要填写到getenv()函数中
            'bucket' => 'project-1310548517', // 换成你的 bucket
            'region' => 'ap-shanghai', // 换成 bucket 所在园区
            'durationSeconds' => 1800, // 密钥有效期
            'allowPrefix' => array('*'), // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allowActions' => array (
                // 简单上传
                'name/cos:PutObject',
                'name/cos:PostObject',
                // 分片上传
                'name/cos:InitiateMultipartUpload',
                'name/cos:ListMultipartUploads',
                'name/cos:ListParts',
                'name/cos:UploadPart',
                'name/cos:CompleteMultipartUpload'
            ),
            // 临时密钥生效条件，关于condition的详细设置规则和COS支持的condition类型可以参考 https://cloud.tencent.com/document/product/436/71306
            // "condition" => array(
            //     "ip_equal" => array(
            //         "qcs:ip" => array(
            //             "10.217.182.3/24",
            //             "111.21.33.72/24",
            //         )
            //     )
            // )
        );
        
        // 获取临时密钥，计算签名
        $tempKeys = $sts->getTempKeys($config);
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$tempKeys]);
    }

    public function upLoadFIle(Request $Request){
        if(!$Request->fileurl){
            return response()->json(['code' => '403', 'msg' => '请选择文件']);
        }
        $secretId = env('UPLOAD_APP_ID'); //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretKey = env('UPLOAD_APP_KEY'); //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $region = "ap-shanghai"; //替换为用户的 region，已创建桶归属的 region 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $cosClient = new \Qcloud\Cos\Client(
            array( 'region' => $region, 'schema' => 'https', 'credentials'=> array( 'secretId'  => $secretId , 'secretKey' => $secretKey))
        );

        $key_upload = $Request->key ? $Request->key : 'user';
        $binaryData = base64_decode($Request->fileurl);
        $tmpfname = tempnam(sys_get_temp_dir(), 'base64');
        file_put_contents($tmpfname, $binaryData);
        $filename = uniqid().'-'.time() . '.png'; // 生成文件名
        try {
            $bucket = "project-1310548517";
            $key = 'wxapp/'.$key_upload.'/'.$filename; //此处的 key 为对象键，对象键是对象在存储桶中的唯一标识
            $file = fopen($tmpfname, 'rb');
            if ($file) {
                $result = $cosClient->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'Body' => $file));
                    $res = 'https://'.$result['Location'];
            }
        } catch (\Exception $e) {
            echo "$e\n";
        }
        return response()->json(['code' => 200, 'data' => $res]);
    }

    public function WxAppOneLoad(Request $Request){
        if(!$Request->fileurl){
            return response()->json(['code' => '403', 'msg' => '请选择文件']);
        }
        $secretId = env('UPLOAD_APP_ID'); //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretKey = env('UPLOAD_APP_KEY'); //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $region = "ap-shanghai"; //替换为用户的 region，已创建桶归属的 region 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $cosClient = new \Qcloud\Cos\Client(
            array( 'region' => $region, 'schema' => 'https', 'credentials'=> array( 'secretId'  => $secretId , 'secretKey' => $secretKey))
        );

        $key_upload = $Request->key ? $Request->key : 'user';
        $binaryData = base64_decode($Request->fileurl);
        $tmpfname = tempnam(sys_get_temp_dir(), 'base64');
        file_put_contents($tmpfname, $binaryData);
        $filename = uniqid().'-'.time() . '.png'; // 生成文件名
        try {
            $bucket = "project-1310548517";
            $key = $key_upload.'/'.$filename; //此处的 key 为对象键，对象键是对象在存储桶中的唯一标识
            $file = fopen($tmpfname, 'rb');
            if ($file) {
                $result = $cosClient->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'Body' => $file));
                    $res = 'https://'.$result['Location'];
            }
        } catch (\Exception $e) {
            echo "$e\n";
        }
        return response()->json(['code' => 200, 'data' => $res]);
    }
}
